package cn.jpanda.elastic.job.autoconfigure;

import cn.jpanda.elastic.job.autoconfigure.properties.ZookeeperProperties;
import com.dangdang.ddframe.job.event.rdb.JobEventRdbConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;
import javax.sql.DataSource;

public class ElasticJobAutoConfiguration {

    /**
     * Zookeeper属性配置
     */
    @Resource
    ZookeeperProperties zookeeperProperties;

    /**
     * 配置Zookeeper注册中心
     *
     * @return Zookeeper注册中心
     */
    @Bean(initMethod = "init")
    @ConditionalOnMissingBean
    public ZookeeperRegistryCenter zookeeperRegistryCenter() {
        assert zookeeperProperties != null:"please config zookeeper .";
        ZookeeperConfiguration zookeeperConfiguration = new ZookeeperConfiguration(
                zookeeperProperties.getServerLists(),
                zookeeperProperties.getNamespace()
        );
        BeanUtils.copyProperties(zookeeperProperties, zookeeperConfiguration);
        return new ZookeeperRegistryCenter(zookeeperConfiguration);

    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean(DataSource.class)
    public JobEventRdbConfiguration jobEventRdbConfiguration(@Autowired DataSource dataSource) {
        return new JobEventRdbConfiguration(dataSource);
    }


}
